<template>
  <div class="cart">
    <h2>购物车</h2>
    <div v-if="cart.length > 0">
      <ul>
        <li v-for="item in cart" :key="item.id">
          <img :src="item.image" alt="商品图片" style="width:80px;" />
          <span>{{ item.name }}</span>
          <span>￥{{ item.price }}</span>
          <span>数量：{{ item.quantity }}</span>
          <button @click="removeFromCart(item.id)">移除</button>
        </li>
      </ul>
      <div class="cart-summary">
        <p>总价：￥{{ totalPrice }}</p>
        <button @click="goToOrder">去结算</button>
      </div>
    </div>
    <div v-else>
      <p>购物车为空</p>
    </div>
  </div>
</template>

<script setup>
// 购物车页面，展示已加入购物车的商品列表
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '../stores/cart'

const cartStore = useCartStore() // 获取购物车状态
const router = useRouter()

// 购物车商品列表
const cart = computed(() => cartStore.cart)
// 计算购物车总价
const totalPrice = computed(() => cartStore.totalPrice)

// 移除商品
function removeFromCart(id) {
  cartStore.removeFromCart(id)
}
// 跳转到下单页
function goToOrder() {
  router.push('/order')
}
</script>

<style scoped>
.cart {
  padding: 20px;
}
.cart-summary {
  margin-top: 20px;
}
</style> 